﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mail;

namespace WLWeb.PulbicClass
{
    public class Webpublic
    {
        public static void ShowMessageAndClose(System.Web.UI.Page page, string message)
        {
            string msg = CsStyledEncode(message);
            page.RegisterStartupScript("MsgScript", "<script language='javascript'>" +
                                                    "function AlertCloseMsg()" +
                                                    "{" +
                                                    "if((window.navigator.userAgent.indexOf('Firefox')>=1) ||document.readyState=='complete'){" +
                                                    "alert('" + msg + "');" +
                                                    "close(); }" +
                                                    "else " +
                                                    "setTimeout('AlertCloseMsg()',1);" +
                                                    "}" +
                                                    "AlertCloseMsg();" +
                                                    "</script>");
        }

        public static void ShowMessage(System.Web.UI.Page page, string message)
        {
            string msg = CsStyledEncode(message);
            page.RegisterStartupScript("MsgScript", "<script language='javascript'>" +
                                                    "function AlertMsg()" +
                                                    "{" +
                                                    "if((window.navigator.userAgent.indexOf('Firefox')>=1) ||document.readyState=='complete')" +
                                                    "alert('" + msg + "');" +
                                                    "else " +
                                                    "setTimeout('AlertMsg()',1);" +
                                                    "}" +
                                                    "AlertMsg();" +
                                                    "</script>");
        }


        public static void ShowWindow(System.Web.UI.Page page, string url, int width, int height, string name)
        {
            page.RegisterStartupScript("ShowFormScript", "<script language='javascript'>" +
                                                         "var winLeft=(window.screen.availWidth-" + width.ToString() + ")/2;" +
                                                         "var winTop=(window.screen.availHeight-" + height.ToString() + ")/2;" +
                                                         "frmWin=window.open('" + url + "','" + name + "','width=" + width.ToString() + ",height=" + height.ToString() +
                                                         ",directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no," +
                                                         "toolbar=no,left='+winLeft+',top='+winTop);" +
                                                         "</script>");
            ////,'','width=" + width.ToString() + "','height=" + height.ToString() + "');" 
        }

        public static string CsStyledEncode(string s)
        {
            s = s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", "\\n").Replace("\n\r", "\\n").Replace("\r", "\\n").Replace("\n", "\\n");
            s = s.Replace("/", "\\/");
            return s;
        }

        /// <summary>
        ///  Send Email to Registered User
        /// </summary>
        /// <param name="UserMail"></param>
        /// <param name="Subject"></param>
        /// <param name="EmailMsg"></param>
        /// <returns></returns>
        public static bool SendMail(string UserMail, string Subject, string EmailMsg)
        {
            try
            {
                string strUserName = System.Configuration.ConfigurationSettings.AppSettings["WebMailUserName"];
                string strPassword = System.Configuration.ConfigurationSettings.AppSettings["WebMailPassword"];
                string strSmtpServer = System.Configuration.ConfigurationSettings.AppSettings["WebMailSmtpServer"];
                string stranonymity = System.Configuration.ConfigurationSettings.AppSettings["WebMailAnonymity"];
                string strFrom = System.Configuration.ConfigurationSettings.AppSettings["WebMailFrom"];

                MailMessage MyMail = new MailMessage();
                MyMail.From = strFrom;
                MyMail.To = UserMail;
                MyMail.Subject = Subject;
                MyMail.Body = EmailMsg;
                MyMail.BodyEncoding = System.Text.Encoding.Default;
                MyMail.BodyFormat = MailFormat.Html;


                if (stranonymity == "False")
                {
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", strUserName); //set your username here
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", strPassword); //set your password here
                }

                SmtpMail.SmtpServer = strSmtpServer;
                SmtpMail.Send(MyMail);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        ///  Send Email to Registered User
        /// </summary>
        /// <param name="UserMail"></param>
        /// <param name="Subject"></param>
        /// <param name="EmailMsg"></param>
        /// <returns></returns>
        public static bool SendMailAttachment(string UserMail, string Subject, string EmailMsg, string strMailAttachment)
        {
            try
            {
                string strUserName = System.Configuration.ConfigurationSettings.AppSettings["WebMailUserName"];
                string strPassword = System.Configuration.ConfigurationSettings.AppSettings["WebMailPassword"];
                string strSmtpServer = System.Configuration.ConfigurationSettings.AppSettings["WebMailSmtpServer"];
                string stranonymity = System.Configuration.ConfigurationSettings.AppSettings["WebMailAnonymity"];
                string strFrom = System.Configuration.ConfigurationSettings.AppSettings["WebMailFrom"];

                MailAttachment objMailAttachment;
                // 创建一个附件对象 
                objMailAttachment = new MailAttachment(strMailAttachment);//

                MailMessage MyMail = new MailMessage();
                MyMail.From = strFrom;
                MyMail.To = UserMail;
                MyMail.Subject = Subject;
                MyMail.Body = EmailMsg;
                MyMail.BodyEncoding = System.Text.Encoding.Default;
                MyMail.BodyFormat = MailFormat.Html;
                MyMail.Attachments.Add(objMailAttachment);

                if (stranonymity == "False")
                {
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", strUserName); //set your username here
                    MyMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", strPassword); //set your password here
                }

                SmtpMail.SmtpServer = strSmtpServer;
                SmtpMail.Send(MyMail);

                return true;

            }
            catch (Exception ex)
            {
                COMMON.ControlCommon.DiskLog("sendmail", ex.Message.ToString());
                return false;
            }
        }

        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddr()
        {
            return !string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        /// <summary>
        /// 根据链接得到分类组别1:套餐;2新闻;3签约4服务5解决方案6技术支持8关于我们
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetGroupName(int Num)
        {
            switch(Num)
            {   
                case 1:
                    return "TaoCan";        //套餐                一个分类一条
                    break;
                case 2:
                    return "news";          //新闻                一个分类多条
                    break;
                case 3:
                    return "QianYue";       //签约                  一个分类多条此组别需要用到开始和结束时间
                    break;
                case 4:
                    return "service";       //服务                  一个分类一条
                    break;
                case 5:
                    return "solution";      //解决方案              一个分类一条
                    break;
                case 6:                     //技术支持              一个分类多条
                    return "IT";
                    break;
                case 8:                     //技术支持              一个分类一条
                    return "about";
                    break;
            }
            return "";
        }
        /// <summary>
        /// 根据参数判断组别是否正确1:套餐;2新闻;3签约4服务5解决方案6技术支持7商品类别8关于我们
        /// </summary>
        /// <param name="Article"></param>
        /// <param name="Num"></param>
        /// <returns></returns>
        public static bool IsGroupName(string Article, int Num)
        {
            if (Num == 1 && Article == "TaoCan")
            {
                return true;
            }
            else if (Num == 2 && Article == "news")
            {
                return true;
            }
            else if (Num == 3 && Article == "QianYue")
            {
                return true;
            }
            else if (Num == 4 && Article == "service")
            {
                return true;
            }
            else if (Num == 5 && Article == "solution")
            {
                return true;
            }
            else if (Num == 6 && Article == "IT")
            {
                return true;
            }
            else if (Num == 7 && Article == "case")
            {
                return true;
            }
            else if (Num == 8 && Article == "about")
            {
                return true;
            }
            return false;
        }


        // <summary>
        /// 判断项目状态
        /// </summary>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public static string IsFinish(string endtime)
        {
            if (Convert.ToDateTime(endtime) > DateTime.Now)
            {
                return "制作中";
            }
            else
            {
                return "已完成";
            }
        }
        #region 创建图片
        //public string GetPic(string ExampleId)
        //{
        //    string where = " WebExampleID='" + ExampleId + "' and Disabled=0 and Sort=1";
        //    WLong.BLL.Rel_WebPicture webpic = new WLong.BLL.Rel_WebPicture();
        //    string picSrc = "";
        //    DataSet ds = webpic.GetList(where);
        //    if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
        //    {
        //        DataTable dtpic = ds.Tables[0];
        //        if (!Directory.Exists(Server.MapPath("../webExamplePic")))
        //        {
        //            Directory.CreateDirectory(Server.MapPath("../webExamplePic"));
        //        }
        //        picSrc = Server.MapPath("../webExamplePic/" + dtpic.Rows[0]["PictureName"].ToString() + ".jpg");
        //        if (!Directory.Exists(picSrc))
        //        {
        //            FileStream fs = new FileStream(picSrc, FileMode.OpenOrCreate, FileAccess.Write);
        //            BinaryWriter bw = new BinaryWriter(fs);
        //            byte[] buf = (byte[])dtpic.Rows[0]["BinaryData"]; //System.Text.Encoding.ASCII.GetBytes(Filecode);
        //            bw.Write(buf);
        //            bw.Close();
        //            fs.Close();
        //        }
        //    }
        //    return picSrc;
        //}
        #endregion
    }
}